package funcs

import (
	"os"
	"compress/gzip"
	"archive/tar"
	"io"
	"path"
	"path/filepath"
	"strings"
	"fmt"
)
type FileUtils struct {

}

func Unzip(srcFilePath string, destDirPath string) error {
	fr, err := os.Open(srcFilePath)
	if err != nil {
		fmt.Println(err)
		return  err
	}
	defer fr.Close()
	gr, err := gzip.NewReader(fr)
	if err != nil {
		fmt.Println(err)
		return  err
	}
	defer gr.Close()
	tr := tar.NewReader(gr)
	var fw *os.File
	defer fw.Close()
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			break
		}
		if hdr.Typeflag != tar.TypeDir && (strings.Contains(hdr.Name,".yaml") || strings.Contains(hdr.Name,".yml")){
			os.MkdirAll(filepath.Join(destDirPath, path.Dir(hdr.Name)), os.ModePerm)
			fw, _ := os.OpenFile(filepath.Join(destDirPath, hdr.Name), os.O_CREATE|os.O_WRONLY, os.FileMode(hdr.Mode))

			if err != nil {
				fmt.Println(err)
				return err
			}
			_, err = io.Copy(fw, tr)
			if err != nil {
				fmt.Println(err)
				return  err
			}
			fw.Close()
		}
	}
	fw.Close()
	return  nil
}